#pragma once
#include "log.hpp"
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

enum {
    SOCKETERR = 2,
    BINDERR,
    LISTENERR,
};

const int backlog = 10;

class Sock
{
public:
    Sock() {}
    ~Sock() {}
public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0) {
            LOG(Fatal, "socket err, %s: %d", strerror(errno), errno);
            exit(SOCKETERR);
        }
        int opt = 1;
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); 
    }
    void Bind(uint16_t port) 
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(sockfd_, (struct sockaddr*)&local, sizeof(local)) < 0) {
            LOG(Fatal, "bind err, %s: %d", strerror(errno), errno);
            exit(BINDERR);
        }
    }
    void Listen()
    {
        if (listen(sockfd_, backlog) < 0) {
            LOG(Fatal, "listen err, %s: %d", strerror(errno), errno);
            exit(LISTENERR);
        }
    }
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int listenfd = accept(sockfd_, (struct sockaddr*)&client, &len);
        if (listenfd < 0) {
            LOG(Warning, "accept err, %s: %d", strerror(errno), errno);
            return -1;
        }
        
        char ipstr[64];
        inet_ntop(AF_INET, &(client.sin_addr), ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(client.sin_port);
        return listenfd;
    }
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(client.sin_addr));
        
        int n = connect(sockfd_, (struct sockaddr*)&client, sizeof(client));
        if (n == -1) {
            LOG(Warning, "connect err, %s: %d", strerror(errno), errno);
            return false;
        }
        return true;
    }
    void Close() 
    {
        close(sockfd_);
    }
    int GetFd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};

